package com.smedi.ismedi.authoritymanagement.core.domain.service.impl;

import com.smedi.ismedi.authoritymanagement.core.domain.aggregatemodel.RoleMember;
import com.smedi.ismedi.authoritymanagement.core.domain.repository.RoleMemberRepository;
import com.smedi.ismedi.authoritymanagement.core.domain.service.RoleBasicDomainService;
import com.smedi.ismedi.authoritymanagement.core.domain.service.RoleMemberDomainService;
import com.smedi.ismedi.authoritymanagement.core.infrastructure.constant.CustomError;
import com.smedi.ismedi.web.starter.exception.LogicException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @Author: xulinjun
 * @Date: 2021-8-11 21:54
 */
@Slf4j
@Service
@AllArgsConstructor
public class RoleMemberDomainServiceImpl implements RoleMemberDomainService {
    private final RoleMemberRepository roleMemberRepository;

    @Override
    public RoleMember saveRoleMember(Long roleId, Long personId) {
        int count = roleMemberRepository.selectCountByRoleIdAndPersonId(roleId, personId);
        if (count > 0) {
            throw LogicException.raise(CustomError.ROLE_MEMBER_DUPLICATE);
        }

        RoleMember roleMember = new RoleMember()
                .setRoleId(roleId)
                .setPersonId(personId);

        return roleMemberRepository.doInsert(roleMember);
    }

    @Override
    public RoleMember queryRoleMemberByRoleMemberId(Long roleMemberId) {
        return roleMemberRepository.selectByRoleMemberId(roleMemberId);
    }

    @Override
    public void deleteRoleMemberByRoleMemberId(Long roleMemberId) {
        RoleMember basic = roleMemberRepository.selectByRoleMemberId(roleMemberId);
        if (basic != null) {
            roleMemberRepository.doDeleteByRoleMemberId(roleMemberId);
        } else {
            throw LogicException.raise(CustomError.ROLE_MEMBER_NOT_EXIST);
        }
    }

    @Override
    public boolean existRoleMember(Long roleId) {
        return roleMemberRepository.selectCountByRoleId(roleId) > 0;
    }
}
